﻿using MySSO.Core.Entity;
using MySSO.Core.Repository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MySSO.Core.Service
{
    public class AdminUserService
    {
        private readonly AdminUserRepository _adminUserRepository;
        private readonly IPService _iPService;
        private readonly AdminUserLoginLogRepository _adminUserLoginLogRepository;
        //private readonly IUserAuthRepository _userAuthRepository;
        private readonly WebHelper _webHelper;
        //private readonly IMenuService _menuService;
        //private readonly IStudentUserRepository _studentUserRepository;

        private readonly int max_num = 5; //账户最大错误次数
        public AdminUserService()
        {
            _adminUserRepository = new AdminUserRepository();
            _iPService = new IPService();
            _adminUserLoginLogRepository =new AdminUserLoginLogRepository();
            
            _webHelper = new WebHelper();
           
        }

        /// <summary>
        /// 获取用户页面权限
        /// </summary>
        /// <param name="adminUserEntity"></param>
        /// <returns></returns>
        //public string GetAdminUserPrograms(AdminUserEntity adminUserEntity)
        //{
        //    if (adminUserEntity == null)
        //    {
        //        return string.Empty;
        //    }
        //    else
        //    {

        //        return _userAuthRepository.GetProgramsByAuth(adminUserEntity.Auths);
        //    }
        //}


        /// <summary>
        /// 根据邮箱获取用户
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public AdminUserEntity GetAdminUserEntityByEmail(string email)
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                return null;
            }
            else
            {
                return _adminUserRepository.GetAdminUserEntityByEmail(email);
            }
        }

        /// <summary>
        /// 根据id获取用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public AdminUserEntity GetAdminUserEntityById(long id)
        {
            return _adminUserRepository.GetAdminUserEntityById(id);
        }

        /// <summary>
        /// 修改管理员
        /// </summary>
        /// <param name="adminUserEntity"></param>
        /// <returns></returns>
        public int UpdateAdminUserEntity(AdminUserEntity adminUserEntity)
        {
            if (adminUserEntity == null)
            {
                throw new NullReferenceException();
            }
            else
            {
                return _adminUserRepository.UpdateAdminUserEntity(adminUserEntity);
            }
        }

        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="email"></param>
        /// <param name="password"></param>
        /// <param name="ip"></param>
        /// <param name="rID"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        public AdminUserEntity Login(string email, string password, string ip, long rID, string clientinfo, out int status)
        {
            status = 0;

            string strstatus;

            string errMessage;
            bool success;

            AdminUserEntity adminUserEntity = this.GetAdminUserEntityByEmail(email);

            if (adminUserEntity == null)
            {
                status = 0;
                strstatus = "返回状态为：" + status;
                errMessage = "Email不存在（" + email + "）";
                success = false;
            }
            else
            {
                if (adminUserEntity.Error_Today.HasValue && adminUserEntity.Error_Today.Value.AddHours(24) > DateTime.Now
                      && adminUserEntity.Today_Login_Error >= max_num)
                {
                    status = -2;
                    strstatus = adminUserEntity.Name;
                    errMessage = "账户输入错误超过5次，被锁定24小时";
                    success = false;
                }
                else if (adminUserEntity.Disable)
                {
                    status = -3;
                    strstatus = adminUserEntity.Name;
                    errMessage = "该账户已被禁用";
                    success = false;
                }

                else if (adminUserEntity.WeakPassword)
                {
                    status = -4;
                    strstatus = adminUserEntity.Name;
                    errMessage = "密码过于简单，又没有在24小时内修改，账户已被锁定。";
                    success = false;
                }

                else if (adminUserEntity.Password != DecryptString.MD5(password))
                {
                    status = -1;
                    strstatus = adminUserEntity.Name;
                    errMessage = "密码错误,密码：" + password;
                    success = false;

                    int error_num = adminUserEntity.Today_Login_Error.HasValue ? adminUserEntity.Today_Login_Error.Value : 0;
                    if (!adminUserEntity.Error_Today.HasValue || adminUserEntity.Error_Today.Value.AddHours(24) < DateTime.Now)
                        error_num = 0;
                    adminUserEntity.Today_Login_Error = error_num + 1;
                    adminUserEntity.Error_Today = DateTime.Now;
                }

                else
                {
                    adminUserEntity.Today_Login_Error = 0;
                    adminUserEntity.Error_Today = DateTime.Now;
                    adminUserEntity.Login_Num = adminUserEntity.Login_Num + 1;
                    adminUserEntity.LastActiveTime = DateTime.Now;
                    adminUserEntity.LastActiveIp = ip;

                    status = 1;
                    strstatus = adminUserEntity.Name;
                    errMessage = "";
                    success = true;
                }

            }

            if (status == -1 || status == 1)
            {
                this.UpdateAdminUserEntity(adminUserEntity);
            }

            if (adminUserEntity == null)
            {
                CreateAdminLoginLog(0, strstatus, ip, success, errMessage, rID, clientinfo);
            }
            else
            {
                CreateAdminLoginLog(adminUserEntity.AUID, strstatus, ip, success, errMessage, rID, clientinfo);
            }


            return adminUserEntity;

        }

        //public AdminUserEntity GetAdminUserEntityFromCache(long auid)
        //{
        //    return _adminUserRepository.GetAllAdminUserByCache().Where(t => t.AUID == auid).FirstOrDefault();
        //}

        //public string GetAdminNameFromCache(long auid)
        //{
        //    AdminUserEntity entity = this.GetAdminUserEntityFromCache(auid);
        //    if (entity != null)
        //    {
        //        return entity.Name;
        //    }
        //    else
        //    {
        //        return "";
        //    }
        //}


        /// <summary>
        /// 创建登录记录
        /// </summary>
        /// <param name="AUID"></param>
        /// <param name="Name"></param>
        /// <param name="Ip"></param>
        /// <param name="Success"></param>
        /// <param name="ErrMessage"></param>
        /// <param name="RID"></param>
        private void CreateAdminLoginLog(long auid, string name, string ip, bool success, string errMessage, long rID, string clientinfo)
        {
            IPCityEntity ipcity = _iPService.GetIPCityByIp(ip);
            string LoginArea = string.Empty;
            if (ipcity != null)
            {
                LoginArea = string.Format("{0} {1} {2}", ipcity.IP_Province, ipcity.IP_City, ipcity.IP_County);
            }
            AdminUserLoginLogEntity adminUserLoginLogEntity = new AdminUserLoginLogEntity();
            adminUserLoginLogEntity.AUID = auid;
            adminUserLoginLogEntity.Name = name;
            adminUserLoginLogEntity.LoginDate = DateTime.Now;
            adminUserLoginLogEntity.IP = ip;
            adminUserLoginLogEntity.LoginArea = LoginArea;
            //待完成
            adminUserLoginLogEntity.ClientInfo = _webHelper.GetClientInfo();
            adminUserLoginLogEntity.Success = success;
            adminUserLoginLogEntity.ErrMessage = errMessage;
            adminUserLoginLogEntity.RID = rID;
            _adminUserLoginLogRepository.InsertAdminUserLoginLogEntity(adminUserLoginLogEntity);
        }






    }
}
